package com.water.tool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 代码生成器
 * 
 * @author whl
 * 
 */
public class FreeMarkerUtil {

	private Configuration cfg;

	public final static String SYSTEM_ENCODING = "UTF-8";

	public void init() throws Exception {
		cfg = new Configuration();
		cfg.setDirectoryForTemplateLoading(new File(
				"F://Project//workspace//Water//WebRoot//template"));
	}

	public void process(FreeMarkerUtil hf, Map root, String projectPath,
			String fileName, String savePath,String ftl) throws Exception {
		Template template = cfg.getTemplate(ftl);
		hf.buildTemplate(root, projectPath, savePath, fileName, template);
	}

	public void buildTemplate(Map root, String projectPath, String savePath,
			String fileName, Template template) {
		String realFileName = projectPath + savePath + fileName;
		String realSavePath = projectPath + "/" + savePath;
		File newsDir = new File(realSavePath);
		if (!newsDir.exists()) {
			newsDir.mkdirs();
		}
		try {
			Writer out = new OutputStreamWriter(new FileOutputStream(
					realFileName), SYSTEM_ENCODING);
			template.process(root, out);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) throws Exception {
		FreeMarkerUtil hf = new FreeMarkerUtil();
		hf.init();
	
		Map root = new HashMap();
		String name = "Article";
		String sortname = "article";
		root.put("name",name);
		root.put("sortname",sortname);
		String projectPath = "F://Project//workspace//Water//";
		String savePath = "src//com//intranet//article//";
		String fileName = "";
		String fly = "";
		
		//Dao
//		fileName = name + "Dao.java";
//		fly = "Dao.ftl";
//		hf.process(hf,root,projectPath,fileName,savePath,fly);
		
		//Service
//		fileName = name + "Service.java";
//		fly = "Service.ftl";
//		hf.process(hf,root,projectPath,fileName,savePath,fly);
		
		//Controller
//		fileName = name + "Controller.java";
//		fly = "Controller.ftl";
//		hf.process(hf,root,projectPath,fileName,savePath,fly);
//		
//		//jsp
//		fileName = sortname + "List.jsp";
//		fly = "jsp.ftl";
//		hf.process(hf,root,projectPath,fileName,savePath,fly);
	}

	public static void maddin() throws Exception {
		FreeMarkerUtil hf = new FreeMarkerUtil();
		hf.init();
		Map root = new HashMap();
		String name = "Employee";
		root.put("name", name);
		root.put("tablename", "water_hr_employee");
		root.put("domainname", "员工表");
		String projectPath = "F://Project//workspace//Water//";
		String fileName = name + ".java";
		String savePath = "src//com//intranet//domain//hr//";
		String fly = "Dao.ftl";
		hf.process(hf,root,projectPath,fileName,savePath,fly);
	}

}